/*
    获取最近的商场
*/
'use strict';
const async = require('async');

module.exports = {
    open: false,
    description: '获取附近商城信息',
    handler(req, res, next){
        let filter = req.query;
        req.mongo.collection("store").indexExists("loc", (e, r) => {
            if (e) return res.err.MongoError(e);
            if (!r) {
                req.mongo.collection("store").createIndex({"loc": "2d"}, (e0, r0) => {
                    if (e0) return res.err.mongoError(e0);
                });
                async.auto([
                    callback =>req.mongo.collection("store").aggregate([
                        {
                            $geoNear: {
                                "near": [filter.longitude, filter.latitude],
                                "distanceField": "loc",
                                "maxDistance": 1,
                                "spherical": true
                            }
                        },
                        { $limit : 1 }
                    ]).next(callback)
                ],(e1, r1) => {
                    if (e1) return res.err.mongoError(e1);
                    return res.reply({code: 0, message: "查询成功", data: r1});
                });
            }
        });
    }
};
